<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="工厂名称" value="1"></el-option>
              <el-option label="英文编码" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 专题管理table -->
    <el-table stripe :data="brandTable" style="width: 100%" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" prop="name" label="型号" min-width="160" align="center" fixed></el-table-column>
      <el-table-column v-if="colData[1].istrue" prop="name_code" label="英文编码" min-width="80" align="center" fixed></el-table-column>
      <el-table-column v-if="colData[2].istrue" prop="ean_code" label="EAN商品码" min-width="150" align="center"></el-table-column>
      <el-table-column v-if="colData[3].istrue" prop="username" label="创建者" min-width="150" align="center"></el-table-column>
      <el-table-column v-if="colData[4].istrue" prop="create_time" label="创建时间" min-width="150" align="center">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[5].istrue" prop="update_time" label="更新时间" min-width="150" align="center">
        <template slot-scope="scope">{{scope.row.update_time| newDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[6].istrue" prop="cpu" label="CPU" min-width="120" align="center"></el-table-column>
      <el-table-column v-if="colData[7].istrue" prop="start_ram" label="运行RAM" min-width="100" align="center"></el-table-column>
      <el-table-column v-if="colData[8].istrue" prop="storage_rom" label="存储ROM" min-width="100" align="center"></el-table-column>
      <el-table-column v-if="colData[9].istrue" prop="display" label="显示屏" min-width="100" align="center"></el-table-column>
      <el-table-column v-if="colData[10].istrue" prop="touch_screen" label="触摸屏" min-width="100" align="center"></el-table-column>
      <el-table-column v-if="colData[11].istrue" prop="prefix_camera" label="前摄像头" min-width="100" align="center"></el-table-column>
      <el-table-column v-if="colData[12].istrue" prop="suffix_camera" label="后摄像头" min-width="100" align="center"></el-table-column>
      <el-table-column v-if="colData[13].istrue" prop="battery" label="电池" min-width="120" align="center"></el-table-column>
      <el-table-column v-if="colData[14].istrue" prop="other" label="其他特殊需求" min-width="120" align="center"></el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button v-permission="['超级管理员','生产管理员']" size="mini" type="primary" @click="getIdDigitsTheres(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="primary" @click="handleDownload(scope.row)">导出</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" :page-sizes="[10, 50, 100, 200]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background
        @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 添加应用专题 -->
    <el-dialog :title="editSubjects ? 'SN生成规则' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
        <el-form-item label="名称" label-width="100px" prop="name">
          <el-input v-model="addForm.name" autocomplete="off" placeholder="请输入产品型号名" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="第三/四位" label-width="100px" prop="nameCode">
          <el-input v-model="addForm.nameCode" autocomplete="off" placeholder="请输入第三/四位英文编码" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="EAN商品码" label-width="100px" prop="ean_code">
          <el-input v-model="addForm.ean_code" autocomplete="off" placeholder="请输入EAN商品码" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="CPU" label-width="100px" prop="firmware.cpu">
          <el-input v-model="addForm.firmware.cpu" autocomplete="off" placeholder="请输入CPU" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="运行RAM" label-width="100px" prop="firmware.start_ram">
          <el-input v-model="addForm.firmware.start_ram" autocomplete="off" placeholder="请输入运行RAM" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="存储ROM" label-width="100px" prop="firmware.storage_rom">
          <el-input v-model="addForm.firmware.storage_rom" autocomplete="off" placeholder="请输入存储ROM" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="显示屏" label-width="100px" prop="firmware.display">
          <el-input v-model="addForm.firmware.display" autocomplete="off" placeholder="请输入显示屏" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="触摸屏" label-width="100px" prop="firmware.touch_screen">
          <el-input v-model="addForm.firmware.touch_screen" autocomplete="off" placeholder="请输入触摸屏" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="前摄像头" label-width="100px" prop="firmware.prefix_camera">
          <el-input v-model="addForm.firmware.prefix_camera" autocomplete="off" placeholder="请输入前摄像头" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="后摄像头" label-width="100px" prop="firmware.suffix_camera">
          <el-input v-model="addForm.firmware.suffix_camera" autocomplete="off" placeholder="请输入后摄像头" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="电池" label-width="100px" prop="firmware.battery">
          <el-input v-model="addForm.firmware.battery" autocomplete="off" placeholder="请输入电池" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="其他备注" label-width="100px" prop="firmware.other">
          <el-input v-model="addForm.firmware.other" autocomplete="off" placeholder="请输入备注信息" class="add_select"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="getaddCreateDigitsThere('ruleForm')" size="mini" round>确 定</el-button>
        <el-button v-else type="primary" @click="getupdateDigitsThere('ruleForm')" size="mini" round>编辑</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import deleteDialog from "@/components/deleteDialog";
import permission from '@/directive/permission/index.js' // 权限判断指令
import { getDigitsThere, addCreateDigitsThere, getIdDigitsThere, updateDigitsThere, exportDigitsThere } from "@/api/snControl.js";
export default {
  directives: { permission },
  components: { dynamicTable, deleteDialog },
  data() {
    let validatorBatchs = (rule, value, callback) => {
      var regex = new RegExp('^(\w|\W|\d){0,2}$')
      var res = regex.test(value);
      if (value.length == 2) {
        callback()
      } else {
        return callback(new Error('请输入两位字符'))
      }
    }
    return {
      checkboxVal: ['型号', '英文编码', 'EAN商品码','创建者', '创建时间', '更新时间', 'CPU', '运行RAM', '存储ROM', '显示屏', '触摸屏', '前摄像头', '后摄像头', '电池', '其他特殊需求'],
      key: 1,
      colData: [],//动态控制table
      brandTable: [],
      select: "", //搜索条件
      searchTable: "",
      total: 0, //总数量
      //批次下拉选择
      lotoptions: [],
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //编辑专题id
      subjectId: 0,
      listQuery: { startSize: 1, pageSize: 10, name: undefined, nameCode: undefined, },
      //添加表单
      addForm: {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        name: '',
        nameCode: '',
        ean_code:'',
        firmware:  { cpu: '', start_ram: '', storage_rom: '', display: '', touch_screen: '', prefix_camera: '', suffix_camera: '', battery: '', other: '' }
      },
      rules: {
        name: [{ required: true, message: "请输入产品型号名", trigger: "blur" }],
        nameCode: [{ validator: validatorBatchs, trigger: "blur" }],
        ean_code: [{ required: true, message: "请输入EAN商品码", trigger: "blur" }, { min:13, max: 13, message: '请输入13位', trigger: 'blur' }],
        'firmware.cpu': [{ required: true, message: "请输入CPU", trigger: "blur" }, { max: 50, message: '最多输入50位', trigger: 'blur' }],
        'firmware.start_ram': [{ required: true, message: "请输入运行RAM", trigger: "blur" }, { max: 50, message: '最多输入50位', trigger: 'blur' }],
        'firmware.storage_rom': [{ required: true, message: "请输入存储ROM", trigger: "blur" }, { max: 50, message: '最多输入50位', trigger: 'blur' }],
        'firmware.display': [{ required: true, message: "请输入显示屏", trigger: "blur" }, { max: 50, message: '最多输入50位', trigger: 'blur' }],
        'firmware.touch_screen': [{ required: true, message: "请输入触摸屏", trigger: "blur" }, { max: 50, message: '最多输入50位', trigger: 'blur' }],
        'firmware.prefix_camera': [{ required: true, message: "请输入前摄像头", trigger: "blur" }],
        'firmware.suffix_camera': [{ required: true, message: "请输入后摄像头", trigger: "blur" }],
        'firmware.battery': [{ required: true, message: "请输入电池", trigger: "blur" }],
        'firmware.other': [{ required: true, message: "请输入备注信息", trigger: "blur" }],
      }
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getDigitsTheres()
  },
  methods: {
    //根据ID查询信息
    getIdDigitsTheres(id) {
      this.subjectId = id
      this.editSubjects = false
      getIdDigitsThere({ id: id }).then(res => {
        this.dialogFormVisible = true
        let data = res.data
        Object.keys(this.addForm.firmware).forEach(key => { this.addForm.firmware[key] = data[key] })
        this.addForm.name = data.name
        this.addForm.nameCode = data.name_code
        this.addForm.ean_code = data.ean_code
      }).catch(err => {
        console.log("请求失败222", err);
      })
    },
    //修改信息
    getupdateDigitsThere(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.id = this.subjectId
          addForm.firmware = JSON.stringify(this.addForm.firmware)
          updateDigitsThere(addForm).then(res => {
            this.$message.success(res.msg)
            this.getDigitsTheres()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //添加SN第三四位数
    getaddCreateDigitsThere(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.firmware = JSON.stringify(this.addForm.firmware)
          addCreateDigitsThere(addForm).then(res => {
            this.$message.success(res.msg)
            this.getDigitsTheres()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    getDigitsTheres() {
      getDigitsThere(this.listQuery).then(res => {
        this.brandTable = res.data
        this.total = res.total
      }).catch(err => {
        this.brandTable = []
        this.total = 0
      })
    },
    //分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getDigitsTheres();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getDigitsTheres();
    },
    //搜索,1，专题名称
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.name = this.searchTable
          this.getDigitsTheres();
          break;
        case '2':
          this.listQuery.nameCode = this.searchTable
          this.getDigitsTheres();
          break;
      }
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, name: undefined, nameCode: undefined, }
      this.getDigitsTheres()
    },
    //表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.addForm = this.$options.data().addForm
      })
    },
    handleDownload(item) {
      exportDigitsThere({userId: localStorage.getItem("ID"), id: item.id}).then(res => {
        console.log('------',res)
        window.open(`https://${res.data.url}`)
      })
      return
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["第三/四位", "CPU", "运行RAM", "存储ROM", "显示屏", "触摸屏", "前摄像头", "后摄像头", "电池", "其他备注"];
        const filterVal = ["nameCode", "CPU", "start_ram", "storage_rom", "display", "touch_screen", "prefix_camera", "suffix_camera", "battery", "other"];
        const list = [{
          "nameCode": item.nameCode, "CPU": item.cpu, "start_ram": item.start_ram, "storage_rom": item.storage_rom, "display": item.display, "touch_screen": item.touch_screen,
          "prefix_camera": item.prefix_camera, "suffix_camera": item.suffix_camera, "battery": item.battery, "other": item.other
        }]
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: 'SN生产管理' });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>
